import Vue from 'vue'
import Vuex from 'vuex'
import { _API_Login, _API_GetUser } from '@/api'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
		code:'', // 微信login后返回的code
        token:'', //用户token
		userInfo:{
			ID: '', //用户id
			Username: '', //姓名
			Avatar: '', //头像
			Sex: '', //性别
			Introduce: '', //签名
			School: '', //学校
			Subject: '', //学科
			Role: 0, //认证中的角色  0：游客，1：学生，2：老师，3：商家，4：院校官方
			State: 0, //当前认证的角色  0：游客，1：学生，2：老师，3：商家，4：院校官方
			MessagesNum: 0, //未读消息数量
			NoticesNum: 0 //未读通知数量
		},
		baseImgUrl:'', //图片地址
    },
    mutations: {
		setCode(state, code){
		    state.code = code
		},
        setToken(state, token){
            state.token = token
        },
		setUserInfo(state, userInfo){
			state.userInfo = userInfo
		},
		updateUserInfo(state,data){
			state.userInfo[data.key] = data.value
		},
		setBaseImgUrl(state,baseImgUrl){
			state.baseImgUrl = baseImgUrl
		}
    },
    actions: {
        login({commit,dispatch}){
			return new Promise((resolve,reject)=>{
				uni.login({
					success(res){
						_API_Login({openid:res.code}).then(res=>{
							uni.setStorageSync('token', res.data)
							commit('setToken',res.data)
							dispatch('getUserInfo')
							resolve()
						}).catch(()=>{
							reject()
						})
					},
					fail() {
						reject()
					}
				})
			})
		},
		getUserInfo({commit}){
			return new Promise((resolve,reject)=>{
				_API_GetUser().then(res=>{
					commit('setUserInfo',res.data)
					resolve(res.data)
				}).catch(()=>{
					reject(res)
				})
			})
		}
    },
    getters: {
		getCode: state => {
		    return state.code
		},
        getToken: state => {
            return state.token
        },
		getUserInfo: state => {
			return state.userInfo
		},
		getUserInfoItem: (state) => (key) => {
			return state.userInfo[key]
		},
		getBaseImgUrl: state =>{
			return state.baseImgUrl
		}
    }
})

export default store